<script setup lang="ts">
import {onMounted, ref} from "vue";
import { useInspectionHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import InspectionFormModal from "@/views/airport/inspection/inspectionList/inspection-form-modal.vue";
import EditPen from "@iconify-icons/ep/edit-pen";
import { InspectionPageResponse } from "@/api/airport/inspection/inspection";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { getDeptTree} from "@/api/system/dept";
import { useRouter } from 'vue-router';
// 引入 Element Plus 图标
import {ElIcon, ElMessage} from 'element-plus';
import { UserFilled,DocumentChecked,List,CircleCheck } from '@element-plus/icons-vue';

const router = useRouter();


const { hasAdminPermission } = useUserStoreHook();
// 批量删除权限控制处理函数
const handleBulkDeleteWithPermission = (tableRef) => {
  debugger
  if (hasAdminPermission) {
    handleBulkDelete(tableRef);
  } else {
    ElMessage.warning("您没有部门负责人权限");
  }
};


/** 组件name最好和菜单表中的router_name一致 */
defineOptions({
  name: "inspectionStart"
});

const inspectionStatusList = useUserStoreHook().dictionaryList["inspection.status"];

const tableRef = ref();

const searchFormRef = ref();

const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getInspectionList,
  handleDelete,
  handleBulkDelete
} = useInspectionHook();

const deptTree = ref([]);
const statusOptions = [
  { label: '计划待提交', value: '0' },
  { label: '计划待审批', value: '1' },
  { label: '计划已驳回', value: '2' },
  { label: '检查待开始', value: '3' },
  { label: '正在检查', value: '4' },
  { label: '已完成', value: '5' }
];

onMounted(async () => {
  try {
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      // 若 data 本身是数组，直接转换
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        // 若 data 不是数组，将其包裹成数组再转换
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});



const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<InspectionPageResponse>();


function openDialog(type: "add" | "update", row?: InspectionPageResponse) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}
function openInspectionCheckPage(inspectionId: number) {
  router.push({
    path: `/airport/inspection/inspectionDetail/index`,
    query: { inspectionId: String(inspectionId) }
  });
}

function openInspectionRecordPage(inspectionId: number) {
  router.push({
    name: 'InspectionCheck', // 确保路由配置中存在该名称
    query: {
      inspectionId: inspectionId.toString()
    }
  });
}

// 新增检查类型选项
const inspectionTypeOptions = [
  { label: '法定自查', value: '1' },
  { label: '安全质量检查', value: '2' },
  { label: '专项检查', value: '3' },
];

</script>
<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="检查计划名称" prop="inspectionName">
        <el-input
          v-model="searchFormParams.inspectionName"
          placeholder="请输入检查计划名称"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="检查对象" prop="deptId">
        <el-cascader
          v-model="searchFormParams.deptId"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
      }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker
          class="!w-[240px]"
          v-model="timeRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="searchFormParams.createBy"
          placeholder="请输入创建人"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="检查类型" prop="inspectionType">
        <el-select
          v-model="searchFormParams.inspectionType"
          placeholder="请选择检查类型"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in inspectionTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(searchFormRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- table bar 包裹  table -->
    <PureTableBar title="检查计划列表" :columns="columns" @refresh="onSearch">
      <!-- 表格操作栏 -->
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增检查计划
        </el-button>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDeleteWithPermission(tableRef)"
        >
          批量删除
        </el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          @click="CommonUtils.exportExcel(columns, dataList, '检查计划列表')"-->
<!--        >单页导出</el-button-->
<!--        >-->
<!--        <el-button type="primary" @click="exportAllExcel">全部导出</el-button>-->
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getInspectionList"
          @page-current-change="getInspectionList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.inspectionId))
          "
        >
          <!-- 添加 inspectionName slot -->
          <template #inspectionName="{ row }">
            <el-button
              link
              type="primary"
              @click="openInspectionCheckPage(row.inspectionId)"
            >
              {{ row.inspectionName }}
            </el-button>
          </template>
          <template #operation="{ row }">
            <!-- 当状态为 0 或 2 时显示编辑、检查项、删除按钮 -->
            <template v-if="row.status === '0' || row.status === '2'">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('update', row)"
              >
                编辑
              </el-button>

              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(AddFill)"
                @click="openInspectionCheckPage(row.inspectionId)"
              >
                检查项
              </el-button>

              <el-popconfirm
                :title="`是否确认删除编号为${row.inspectionId}的这个检查计划`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="danger"
                    :size="size"
                    :icon="useRenderIcon(Delete)"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-if="row.status === '1'">
              <el-button
                class="reset-margin"
                link
                type="warning"
                :size="size"
                @click="openInspectionCheckPage(row.inspectionId)"
              >
                <el-icon><DocumentChecked /></el-icon>
                审批
              </el-button>
            </template>
            <!-- 当状态为 3 或 4 时显示安全检查按钮 -->
            <template v-if="row.status === '3' || row.status === '4'">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                @click="openInspectionCheckPage(row.inspectionId)"
              >
                <el-icon><CircleCheck /></el-icon>
                安全检查
              </el-button>
            </template>
            <!-- 当状态为 5 或 4 时显示查看检查记录按钮 -->
            <template v-if="row.status === '5'">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                @click="openInspectionRecordPage(row.inspectionId)"

              >
                <el-icon><List /></el-icon>
                检查记录
              </el-button>
            </template>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <inspection-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="onSearch"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
